package cc.liyinghao.springsecuritydemo.controller;

import cc.liyinghao.springsecuritydemo.common.Result;
import cc.liyinghao.springsecuritydemo.pojo.User;
import cc.liyinghao.springsecuritydemo.pojo.param.UserLoginParam;
import cc.liyinghao.springsecuritydemo.pojo.param.UserRegisterParam;
import cc.liyinghao.springsecuritydemo.service.UserService;
import io.swagger.annotations.Tag;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

/**
 * 登录相关接口
 */
@RestController
@RequiredArgsConstructor
public class LoginController {

    @Value("${jwt.tokenHead}")
    private String tokenHead;
    private final UserService userService;

    @PostMapping("/register")
    public Result<String> register(@Validated @RequestBody UserRegisterParam userRegisterParam) {
        User user = userService.register(userRegisterParam);
        if (user == null) {
            return Result.error("注册失败");
        }
        return Result.success("注册成功");
    }

    @PostMapping("/login")
    public Result<Map<String, String>> login(@Validated @RequestBody UserLoginParam umsAdminLoginParam) {
        String token = userService.login(umsAdminLoginParam.getUsername(), umsAdminLoginParam.getPassword());
        if (token == null) {
            return Result.error("用户名或密码错误");
        }
        Map<String, String> tokenMap = new HashMap<>();
        tokenMap.put("token", token);
        tokenMap.put("tokenHead", tokenHead);
        return Result.success(tokenMap);
    }
}
